import { bus } from '@/main.js';
import { DTRange } from '@/components/def-option.js';
import _ from 'lodash';

import { mapState, mapMutations } from 'vuex';
export default {
  name: 'mainDate',
  computed: {
    ...mapState(['conditional', 'userInfo', 'dialog']),
    optionsBelongToSales: function() {
      let opts = this.conditional.belongToSales.options.slice(1);
      // let pid = this.parameter.department;
      // if (pid == '') {
      //   return opts;
      // } else {
      //   return opts.filter(v => {
      //     return v.pid == pid;
      //   });
      // }
      return opts;
    },
    theServicePage: function() {
      return {
        start: this.page.current,
        length: this.page.size,
      };
    },
    theConditions: function() {
      let p = this.parameter;
      let $moment = this.$moment;
      function formatTime(t) {
        if ($moment(t).isValid()) {
          return $moment(t).format('YYYY-MM-DD HH:mm:ss');
        } else {
          return '';
        }
      }
      return {
        nickName: _.get(p, 'nickname', ''),
        isAttentionWeChatWorkbench: _.get(p, 'focusOn', ''),
        isBubb: _.get(p, 'isBubb', ''),
        isRepetition: _.get(p, 'repeatResources', ''),
        isGlobalPhonenumberRep: _.get(p, 'globalRepeat', ''),
        deleteStatus: _.get(p, 'flagDelete', ''),
        eS_Company_Id: _.get(p, 'workbench', []).join(','),
        jxBeginTime: formatTime(_.get(p, 'releaseTime[0]', '')),
        jxEndTime: formatTime(_.get(p, 'releaseTime[1]', '')),
        jhBeginTime: formatTime(_.get(p, 'jhTime[0]', '')),
        jhEndTime: formatTime(_.get(p, 'jhTime[1]', '')),

        deleteBeginTime: formatTime(_.get(p, 'deleteBeginTime[0]', '')),
        deleteEndTime: formatTime(_.get(p, 'deleteBeginTime[1]', '')),
        tagid: _.get(p, 'theLabel', []).join(','),
        zyQd: _.get(p, 'resourceChannels', []).join(','),
        deptId: _.get(p, 'department', '').join(','),
        saleMan: _.get(p, 'belongToSales', []).join(','),
        searchUserId: _.get(p, 'searchUserId', []).join(','),
        phoneNumber: _.get(p, 'phoneNumber', ''),
        isLoginStatus: _.get(p, 'isLoginStatus', []).join(','),
        isInstallationIndicators: _.get(p, 'isInstallationIndicators', []).join(
          ',',
        ),
        isAttentionWeChatWorkbench: _.get(
          p,
          'isAttentionWeChatWorkbench',
          [],
        ).join(','),
        joinGroup_State: _.get(p, 'joinGroup_State', ''),
        blackState: _.get(p, '开发资源排查', ''),
      };
    },
  },
  data() {
    return {
      isDev: process.env.NODE_ENV == 'development',
      COLOR_Red: '#f53f3f',
      COLOR_Orange: '#f77234',
      bus: bus,

      dataTimeRangePicker: [
        { label: '今日', value: DTRange.today },
        { label: '昨日', value: DTRange.yesterday },
        { label: '近7日', value: DTRange.nearly7D },
        { label: '本月', value: DTRange.thisMonth },
        { label: '上月', value: DTRange.nearly1M },
      ],
      quickResetPicker: (() => {
        const BASE = {
          focusOn: '', //是否关注
          repeatResources: '', //是否重复资源
          flagDelete: '', //是否删除
        };
        return [
          { label: '全部进线', value: {} },
          { label: '重复进线', value: { repeatResources: '1' } },
          { label: '去重', value: { repeatResources: '0' } },
          // { label: "已关注", value: { focusOn: "1" } },
          // { label: "未关注", value: { focusOn: "0" } },
          { label: '已删除', value: { flagDelete: '1' } },
        ].map(v => {
          v.value = Object.assign({}, BASE, v.value);
          return v;
        });
      })(),
      optsWXid: [],
      opts开发资源排查: [
        {
          label: '正常',
          value: 1,
        },
        {
          label: '异常',
          value: 2,
        },
      ],
      parameter: {
        nickname: '', //昵称
        resourceChannels: [], //资源渠道
        focusOn: '', //是否关注
        repeatResources: '', //是否重复资源
        flagDelete: '', //是否删除
        workbench: [], //工作台
        department: [], //部门
        belongToSales: [], //归属销售
        searchUserId: [], //联动归属销售
        theLabel: [],
        releaseTime: [], //发布时间
        phoneNumber: '', //电话号码
        lastLoginTime: [],
        isLoginStatus: [],
        isInstallationIndicators: [],
        isAttentionWeChatWorkbench: [],
        sortColumn: '',
        sortType: '',
        joinGroup_State: '',
        开发资源排查: '',
      },
      stateData: {
        总添加: 0,
        重复添加: 0,
        重复率: 0,
        新增添加: 0,
        新增添加率: 0,
        工作台冒泡率: 0,
        关注数: 0,
        关注率: 0,
        删除数: 0,
        删除率: 0,
      }, // 显示数据统计之和用
      tableData: [],
      tableSelectedRowId: [],
      loading: false,
      loading2: false,
      FlagErr: 0,
      multipleSelection: [], //被选中的孩子
      page: {
        current: 1,
        size: 20,
        total: 40,
      },
    };
  },
  watch: {
    'userInfo.company_Employee_Id': {
      handler: function(nv, ov) {
        if (nv == 0) {
          return;
        }
        this.ajaxData(true);
      },
      immediate: true,
    },
  },
  filters: {
    getMinWidth(opt) {
      let arrLen = opt.map(v => {
        return v.label.length;
      });
      return `${Math.max(...arrLen) * 14 + 30}px`;
    },
    esId2esName(group, opt) {
      return group.map(v => {
        let temp = opt.find(item => {
          return item.value == v.value;
        });
        let label = temp == undefined ? '未知' : temp.label;
        return Object.assign({ label: label }, v);
      });
    },
    value2Label(val, opt) {
      let item = opt.find(item => {
        return item.value === val;
      });
      if (item == undefined) {
        return val;
      }
      return item.label;
    },
  },
  methods: {
    按员工id加载员工微信id: function(arr) {
      let opts = this.optionsBelongToSales;
      let r = arr
        .map(txt => {
          let item = opts.find(va => {
            return va.label == txt;
          });
          return item.key;
        })
        .join(',');
      this.$api
        .员工userid下发({
          companyEmployeeId: r,
        })
        .then(res => {
          console.log(res);
          if (res.code == 200) {
            this.optsWXid.splice(0, this.optsWXid.length);
            res.data.forEach((v, i) => {
              this.optsWXid.push({
                key: i,
                label: `${v.userid}- ${v.companyName}-${v.eS_Company_Id}`,
                value: v.userid,
              });
            });
          }
        })
        .catch(err => {
          console.error(err);
        })
        .finally(_ => {});
    },
    调用会话存档: function(row) {
      bus.$emit('调用会话存档', row);
    },
    准备报表审核: function(row) {
      bus.$emit('准备报表审核', row);
    },
    reShowPhone: function(row) {
      let tel = this._.get(row, 'allPhoneNumber[0].phoneNumber', '');
      let t = this._.get(row, 'addTime', ''); //具体取哪个时间还没确定
      if (!this.$moment(t).isValid()) {
        return tel;
      }
      let isNow = this.$moment().diff(this.$moment(t), 'hours') < 24;
      if (isNow) {
        return tel;
      } else {
        return tel
          .split('')
          .reduce((t, v, i, a) => {
            let min = Math.min(3, (a.length - 3) / 2);
            let max = Math.min(4, (a.length - 4) / 2);
            if (i >= min && i <= a.length - 1 - max) {
              t.push('*');
            } else {
              t.push(v);
            }
            return t;
          }, [])
          .join('');
      }
    },
    reAjaxBelongToSales: function(event) {
      this.parameter.belongToSales.splice(
        0,
        this.parameter.belongToSales.length,
      );
    },
    setTheadClass: function(row, rowIndex) {
      return 'info-row';
    },
    quickReset(val) {
      Object.assign(this.parameter, val);
      this.ajaxData(true);
    },
    quickSetupTime(val) {
      this.parameter.releaseTime = val;
      this.ajaxData(true);
    },
    ajaxData(isToPage1) {
      if (isToPage1) {
        this.page.current = 1;
      }
      let arg = Object.assign(
        {},
        this.$store.getters['userInfo/getEmployee'],
        this.theConditions,
        this.theServicePage,
      );
      this.loading = true;
      this.$api
        .getScrmFollowUserList({}, arg)
        .then(res => {
          console.log(
            '%c [ res ]-295',
            'font-size:13px; background:pink; color:#bf2c9f;',
            res,
          );
          if (res.data.data.length < 0) {
            return Promise.reject(
              '请求长度为0，可能是员工id为0的缘故，请自行排查',
            );
          }
          this.page.total = _.get(res, 'data.recordsTotal', 0);
          return Promise.resolve(res.data.data);
        })
        .then(res => {
          this.tableData.splice(0, this.tableData.length);
          res.forEach(v => {
            if (v.tagId == null) {
              v.tagId = [];
            } else {
              v.tagId = v.tagId.split(',');
            }
            if (v.tagString == null) {
              v.tagString = [];
            } else {
              v.tagString = v.tagString.split(',');
            }
            this.tableData.push(v);
          });
          this.FlagErr = 0;
          this.loading = false;
          this.loading2 = true;
          return this.$api.getScrmFollowStatistics({}, arg);
        })
        .then(res => {
          if (res.code == 200) {
            this.setState(res.data);
            this.loading2 = false;
          }
        })
        .catch(err => {
          console.error(err);
          this.$nextTick(() => {
            // 用计数器检测是否多次出现相同问题
            this.FlagErr++;
            if (this.FlagErr < 5) {
              this.loading = true;
              this.ajaxData(isToPage1);
            } else {
              this.loading = false;
              this.$message({ message: '数据请求异常', type: 'error' });
            }
          });
        })
        .finally(() => {
          // this.loading = false;
        });
    },
    setState(data) {
      // this.stateData.工作台冒泡 = data.bubbNumber;//这个没有在图上也没有在vue.data中定义
      this.stateData.工作台冒泡率 = data.bubbRate;
      this.stateData.删除数 = data.deleteByExternalUser;
      this.stateData.删除率 = data.deleteByExternalUserRate;
      this.stateData.总添加 = data.incomingLineNumber;
      this.stateData.新增添加 = data.newIncomingLineNumber;
      this.stateData.新增添加率 = data.newAttentionRate;
      this.stateData.关注数 = data.numberOfFollowers;
      this.stateData.关注率 = data.numberOfFollowersRate;
      this.stateData.重复添加 = data.repeatNumber;
      this.stateData.重复率 = data.repeatRate;
    },
    search() {
      if (this.tableSelectedRowId.length > 0) {
        let s = this.tableSelectedRowId;
        let nTable = this.tableData.filter(r => {
          return s.includes(r.id);
        });
        this.tableData.splice(0, this.tableData.length);
        nTable.forEach(v => {
          this.tableData.push(v);
        });
        return;
      }
      this.ajaxData(true);
    },
    reset() {
      this.$refs['table'].clearSelection();
      this.parameter = this.$options.data().parameter;
      this.ajaxData(true);
    },
    refresh() {
      this.$refs['table'].clearSelection();
      this.ajaxData(false);
    },
    editNote(row) {
      // console.log(row)
      this.$store.commit('toggleDialog', {
        type: 'dialog',
        key: '编辑备注',
        tempData: row,
      });
    },
    editTheLabel(row) {
      this.$store.commit('toggleDialog', {
        type: 'dialog',
        key: '编辑标签',
        tempData: row,
      });
    },
    dialNumberManagement(row, step) {
      this.$store.commit('openDialogPhoneManagement', {
        step: step,
        tempData: row,
      });
    },

    clinchADeal(row) {
      this.$store.commit('toggleDialog', {
        type: 'drawer',
        key: '成交登记',
        tempData: this._.cloneDeep(row),
      });
    },
    handleSortChange({ column, prop, order }) {
      this.parameter.sortColumn = prop;
      this.parameter.sortType = order == 'ascending';
      this.$nextTick(() => {
        this.ajaxData(false);
      });
    },
    handleCheckedAsSwitch($event) {
      if ($event.length > 1) $event.shift();
    },
    handleSelectionChange(val) {
      // val 是被选中的完整数组对象，如不需完整对象请自行map
      let rowMapId = val.map(v => {
        return v.id;
      });
      this.tableSelectedRowId.splice(0, this.tableSelectedRowId.length);
      val.forEach(v => {
        this.tableSelectedRowId.push(v.id);
      });
      this.$store.commit('setCustomerChangeList', rowMapId);
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.ajaxData(false);
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.ajaxData(false);
    },
    updataPhone({ id, allPhoneNumber }) {
      let idx = this.tableData.findIndex(v => {
        return v.id == id;
      });
      if (idx == -1) {
        return;
      }
      let tar = this._.get(this.tableData[idx], 'allPhoneNumber');
      tar.splice(0, tar.length);
      allPhoneNumber.forEach(v => {
        tar.push(v);
      });
    },
    updataRemark({ id, remarks }) {
      let tar = this.tableData.find(v => {
        return v.id == id;
      });
      if (tar == undefined) {
        return;
      }
      tar.remark = remarks;
    },
    updataTheLabel({ id, arrTag }) {
      let idx = this.tableData.findIndex(v => {
        return v.id == id;
      });
      if (idx < 0) {
        return;
      }
      let tar = this.tableData[idx];
      tar.tagId.splice(0, tar.tagId.length);
      tar.tagString.splice(0, tar.tagString.length);
      arrTag.forEach(v => {
        tar.tagId.push(v.tagid);
        tar.tagString.push(v.tagName);
      });
    },
    set访问状态($event, row) {
      // this.$message({
      //   type: 'error',
      //   message: '前端提示：数据未接入',
      //   duration: 1000 * 0.5,
      //   onClose: () => { row.isAccessToRoom = !row.isAccessToRoom; }
      // })
      // return//后面是正式可用的
      let arg = {
        id: this._.get(row, 'id'),
        isAccessToRoom: $event,
      };
      this.$api
        .updata访问状态(arg, {})
        .then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '修改成功',
            });
          }
        })
        .catch(err => {
          this.$message({
            type: 'error',
            message: '修改被拒绝',
            duration: 1000 * 0.5,
            onClose: () => {
              row.isAccessToRoom = !row.isAccessToRoom;
            },
          });
        });
    },
    查看开发资源排查数据(row) {
      let _ = this._;
      console.log(row);
      let p = {
        pn_Resources_Id: row.pn_Resources_Id,
      };
      this.$api
        .查看开发资源排查数据(p)
        .then(res => {
          console.log(
            '%c [ res ]-518',
            'font-size:13px; background:pink; color:#bf2c9f;',
            res,
          );
          if (res.code == 200 && res.data) {
            this.$msgbox({
              title: '开发资源排查结果',
              dangerouslyUseHTMLString: true,
              message: `排查结果：${res.data.stateString}<br>最近更新时间：${res.data.updTimeString}`,
            });
          }
        })
        .catch(err => {
          console.error(err);
        })
        .finally(_ => {});
    },
  },
  mounted: function() {
    bus.$on('updataPhone', ({ id, allPhoneNumber }) => {
      this.updataPhone({ id, allPhoneNumber });
    });
    bus.$on('updateRemark', ({ id, remarks }) => {
      this.updataRemark({ id, remarks });
    });
    bus.$on('updataTheLabel', ({ id, arrTag }) => {
      this.updataTheLabel({ id, arrTag });
    });
    bus.$on('更新某客户描述', ({ id, description }) => {
      let tar = this.tableData.find(v => {
        return v.id == id;
      });
      if (tar == undefined) {
        return;
      }
      tar.description = description;
    });
    bus.$on('更新工作台资源绑定', ({ id, pn_Resources_Id }) => {
      let tar = this.tableData.find(v => {
        return v.id == id;
      });
      if (tar == undefined) {
        return;
      }
      tar.pn_Resources_Id = pn_Resources_Id;
    });
    bus.$on('成交登记变更', e => {
      this.ajaxData(false);
    });
  },
};
